import {judgeFormDataExistModify} from './formUtil'
import {WfForm} from '../interface'
import trim from 'lodash/trim'

//获取表单数据
export const getformdatas = (workflowReqForm) =>{
	const mainData = workflowReqForm.get('mainData');
	const detailData = workflowReqForm.get('detailData');
	let formarea = {};
    mainData.mapEntries && mainData.mapEntries(f => {
    	f[1].mapEntries(o =>{
    		if(o[0] == 'value') {
    			const fieldname = updateHiddenSysFieldname(f[0]);
    			formarea[fieldname] = o[1];
    		}
    		if(o[0] == "groupnum"){
                const groupnum  = o[1];
                for(let i = 0 ;i<groupnum;i++){
                	if(f[1].has(`group_${i}`)){
                        formarea[`${f[0]}group${i}`] = f[1].get(`group_${i}`);
					}
                }
                formarea[`${f[0]}groupnum`] =groupnum;
            }
		});
    });
	detailData && detailData.map((v,k) => {
		const detailIndex = parseInt(k.substring(7))-1;
		let submitdtlid = "";
		v.get("rowDatas").map((datas, rowKey) => {
			const rowIndex = parseInt(rowKey.substring(4));
			submitdtlid += rowIndex+",";
			datas.mapEntries && datas.mapEntries(f => {
				if(f[0] === "keyid"){
					formarea[`dtl_id_${detailIndex}_${rowIndex}`] = f[1];
				}else if(f[0].indexOf("field") > -1){
					const domfieldvalue = f[1] && f[1].get("value");
					const domfieldid = f[0]+"_"+rowIndex;
					formarea[domfieldid] = domfieldvalue;
				}
			});
		});
		formarea[`nodesnum${detailIndex}`] = v.get("rowDatas").size;
        formarea[`indexnum${detailIndex}`] = v.get("indexnum");
        formarea[`submitdtlid${detailIndex}`] = submitdtlid;
        formarea[`deldtlid${detailIndex}`] = (v.get("deldtlid")||"");
	});
    return formarea;
}

//处理系统字段名称 
export const updateHiddenSysFieldname = (fieldname) => {
	switch(fieldname){
		case 'field-1':
			return 'requestname';
		case 'field-2':
			return 'requestlevel';
		case 'field-3':
			return 'messageType';
		case 'field-5':
			return 'chatsType';
		default:
			return fieldname;
	}
}

//流程提交前相关操作
export const doBefore = (src,params,isaffirmance) => {
	//console.log("params",params);
	//post前调用公共方法
	let ischeckok = true;
	if(typeof(doBeforeReqSubmt) == "function"){
        ischeckok = doBeforeReqSubmt(params);
	}
	//old
	if('submit' === src || isaffirmance === '1'){
		if(typeof(checkCustomize) == "function"){
            ischeckok = checkCustomize();
		}
		if(typeof(checkCarSubmit) == "function"){
            ischeckok = checkCarSubmit();
		}
	}
	return ischeckok;
}

//签字意见获取光标，并滚动签字意见框到可视区域
export const signMustInputTips = () =>{
	let  remarktop = parseInt(jQuery("#remark").offset().top);
	if(remarktop == 0){
		remarktop = parseInt(jQuery("#remarkShadowDiv").offset().top);
	}
	let scrolltop = 0;
	//判断意见框是否在可视区域
	
	const isVisual = remarktop > 0 && (remarktop - jQuery('.wea-new-top-req').height() + 200 <  jQuery('.wea-new-top-req-content').height());
	if(!isVisual) {
		if(remarktop - jQuery('.wea-new-top-req').height() + 200 > jQuery('.wea-new-top-req-content').height()){
			scrolltop = remarktop + jQuery('.wea-new-top-req-content').scrollTop() - 185;
		}
		if(remarktop <  (jQuery('.wea-new-top-req').height())){
			if(remarktop < 0) remarktop = remarktop * -1;	
			scrolltop = jQuery('.wea-new-top-req-content').scrollTop() - remarktop - jQuery('.wea-new-top-req').height() -100;
		}
		jQuery('.wea-new-top-req-content').animate({ scrollTop: scrolltop + "px" }, 0);
	}
	
	UE.getEditor('remark').focus(true);
}

//获取签字意见数据
export const getSignInputInfo = () =>{
	const remarkDiv = jQuery('#remark_div');
	return {
		signworkflowids:remarkDiv.find('#signworkflowids').val()||"",
		signdocids:remarkDiv.find('#signdocids').val()||"",
		remarkLocation:remarkDiv.find('#remarkLocation').val()||"",
		'field-annexupload':remarkDiv.find('#field-annexupload').val()||"",
		'field_annexupload_del_id':remarkDiv.find('#field_annexupload_del_id').val(),
		'field-annexupload-name':remarkDiv.find('#field-annexupload-name').val()||"",
		'field-annexupload-count':remarkDiv.find('#field-annexupload-count').val()
	};
}

//待办、门户列表刷新
export const listDoingRefresh =()=>{
	try{
		window.opener._table.reLoad();
	}catch(e){}
	try{
		//刷新门户流程列表
		jQuery(window.opener.document).find('#btnWfCenterReload').click();
	}catch(e){}
}

//获取自由流程节点数据
export const getFreeNodeData = (isFree)=>{
	let freeNodeInfo  = {};
	if("1" == isFree){
		jQuery('.freeNode').find('input').map((o,k)=>{
			freeNodeInfo[k.name] = k.value;
		});
	}
	return freeNodeInfo;
}

//签字意见验证
export const chekcremark = (remarkcontent) => {
	let hasvalue = true;
	if(remarkcontent == null) {
		hasvalue = false;
	} else {
		while(remarkcontent.indexOf(" ") >= 0) {
			remarkcontent = remarkcontent.replace(" ", "");
		}
		while(remarkcontent.indexOf("\\n") >= 0) {
			remarkcontent = remarkcontent.replace("\r\n", "");
		}
	}
	if(trim(remarkcontent).length  === 0) {
		hasvalue = false;
	}
	return hasvalue;
}

//当关闭表单或者刷新表但时提示
const doFormBeforeunload = () =>{
	const reqIsSubmit  = window.store_e9_workflow.getState().workflowReq.get("reqIsSubmit");
	if(!reqIsSubmit && judgeFormDataExistModify(WfForm.getReqFormState()))
        return "流程还没保存，如果离开，将会丢失数据，真的要离开吗？";
}

window.doFormBeforeunload = doFormBeforeunload;

//图片轮播下载事件
window.downloads = (fileid) =>{
	document.location.href = "/weaver/weaver.file.FileDownload?download=1&fileid="+fileid;
}

//获取签名信息
export const getReqAuthSignature = (reqState) =>{
	if(reqState){
		const authStr = reqState.getIn(["params","authStr"]);
		const authSignatureStr = reqState.getIn(["params","authSignatureStr"]);
		return {authStr:authStr,authSignatureStr:authSignatureStr};
	}
	return {};
}

//获取主次账号信息
export const getReqBelUserInfo = (reqState) =>{
	let belUser = {};
	if(reqState){
		belUser["f_weaver_belongto_userid"] = reqState.getIn(["params", "f_weaver_belongto_userid"]);
		belUser["f_weaver_belongto_usertype"] = reqState.getIn(["params", "f_weaver_belongto_usertype"]);
	}
	return belUser;
}

window.onbeforeunload = (e) =>{
  e = e || window.event;
  const reqIsSubmit  = window.store_e9_workflow.getState().workflowReq.get("reqIsSubmit");
  const isUnbeforeunload  = window.store_e9_workflow.getState().workflowReq.get("isUnbeforeunload");
  const doneForm  = window.store_e9_workflow.getState().workflowReq.getIn(["params","requestType"]) === 0;
  if(isUnbeforeunload && !doneForm && !reqIsSubmit && judgeFormDataExistModify(WfForm.getReqFormState())){
  	const tipMsg  = "流程还没保存，如果离开，将会丢失数据，真的要离开吗？";
	  if (e) {
	    e.returnValue = tipMsg;
	  }
	  return tipMsg;
  }
}
